import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { loginAndBack } from './aaa'

// create an axios instance
//console.log('VUE_APP_BASE_API', process.env)
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  //baseURL: "/a",
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['x-token'] = store.getters.token
    }
    config.headers['Site'] = store.getters.site
    //由于某些查询不需要biz，请在请求的地方加上
    //config.headers['Biz'] = store.getters.biz
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    /*if (response.status !== 200 && res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // invalid or expired token
     /!* if (response.status === 401) {
        // console.log(11);
        if (getToken()) {
          store.commit('user/Logout')
          top.location.href = process.env.VUE_APP_LOGIN_API
          // console.log(11);
        }
      }*!/

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      return Promise.reject(new Error(res.message || 'Error'))
    } else {*/

    return res
    //}
  },
  error => {
    if (error.response !== undefined && error.response.status === 401) {
      loginAndBack()
    }
    return Promise.reject(error)
  }
)

export default service
